<template>
  <div class="diagnosis-container">
    <div class="page-header">
      <h1>诊断与治疗计划</h1>
      <div class="patient-selector">
        <span>当前患者：</span>
        <el-select 
          v-model="selectedPatientId" 
          filterable 
          placeholder="请选择患者" 
          @change="handlePatientChange"
          class="patient-select"
        >
          <el-option
            v-for="patient in patients"
            :key="patient.id"
            :label="patient.name + ' (ID: ' + patient.id + ')'"
            :value="patient.id"
          >
            <div class="patient-option">
              <div class="patient-option-info">
                <div>{{ patient.name }}</div>
                <div class="patient-option-id">ID: {{ patient.id }}</div>
              </div>
            </div>
          </el-option>
        </el-select>
      </div>
    </div>

    <div v-if="selectedPatient" class="patient-info-card">
      <el-card>
        <div class="patient-info-header">
          <div class="patient-basic-info">
            <h2>{{ selectedPatient.name }}</h2>
            <div class="patient-details">
              <span><el-icon><User /></el-icon> {{ selectedPatient.gender === 0 ? '男' : '女' }}, {{ selectedPatient.age }}岁</span>
              <span><el-icon><Phone /></el-icon> 联系方式: {{ selectedPatient.contact }}</span>
              <span><el-icon><Calendar /></el-icon> 入院日期: {{ formatDate(selectedPatient.admissionDate) }}</span>
              <el-tag :type="selectedPatient.patientStatus === 0 ? 'success' : 'danger'">
                {{ selectedPatient.patientStatus === 0 ? '正常' : '异常' }}
              </el-tag>
            </div>
          </div>
          <div class="patient-actions">
            <el-button type="primary" @click="handleEditDiagnosis">
              <el-icon><Edit /></el-icon> 编辑诊断
            </el-button>
            <el-button @click="handlePrintReport">
              <el-icon><Printer /></el-icon> 打印报告
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <div v-if="selectedPatient" class="diagnosis-content">
      <el-row :gutter="20">
        <el-col :span="16">
          <el-tabs v-model="activeTab" class="diagnosis-tabs">
            <el-tab-pane label="诊断信息" name="diagnosis">
              <el-card class="diagnosis-card">
                <template #header>
                  <div class="card-header">
                    <span>诊断信息</span>
                    <span class="diagnosis-date" v-if="latestDiagnosis">更新于: {{ formatDate(latestDiagnosis.diagnosisDate) }}</span>
                  </div>
                </template>
                <div v-if="diagnosisList.length > 0">
                  <div class="diagnosis-section">
                    <h3>诊断记录</h3>
                    <div class="diagnosis-list">
                      <div v-for="(diagnosis, index) in diagnosisList" :key="index" class="diagnosis-item">
                        <span class="diagnosis-result">{{ diagnosis.diagnosisResult }}</span>
                        <span class="diagnosis-date">{{ formatDate(diagnosis.diagnosisDate) }}</span>
                      </div>
                    </div>
                  </div>
                </div>
                <div v-else class="empty-data">
                  <el-empty description="暂无诊断记录" />
                  <el-button type="primary" @click="handleEditDiagnosis">添加诊断</el-button>
                </div>
              </el-card>

              <el-card class="treatment-plan-card">
                <template #header>
                  <div class="card-header">
                    <span>治疗计划</span>
                    <el-button type="primary" link @click="handleEditTreatment">
                      <el-icon><Edit /></el-icon> 编辑计划
                    </el-button>
                  </div>
                </template>
                <div v-if="treatmentPlansList.length > 0">
                  <div class="treatment-section">
                    <h3>治疗方案</h3>
                    <el-timeline>
                      <el-timeline-item
                        v-for="(treatment, index) in treatmentPlansList"
                        :key="index"
                        :timestamp="`${formatDate(treatment.startDate)} - ${formatDate(treatment.endDate)}`"
                      >
                        <h4>治疗计划 #{{ treatment.id }}</h4>
                        <p>{{ treatment.treatmentDescription }}</p>
                      </el-timeline-item>
                    </el-timeline>
                  </div>
                </div>
                <div v-else class="empty-data">
                  <el-empty description="暂无治疗计划" />
                  <el-button type="primary" @click="handleEditTreatment">添加治疗计划</el-button>
                </div>
              </el-card>
            </el-tab-pane>
            <el-tab-pane label="病情记录" name="condition">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>病情记录</span>
                    <el-button type="primary" link @click="handleAddConditionRecord">
                      <el-icon><Plus /></el-icon> 添加记录
                    </el-button>
                  </div>
                </template>
                <div v-if="conditionRecordsList.length > 0">
                  <el-timeline>
                    <el-timeline-item
                      v-for="(record, index) in conditionRecordsList"
                      :key="index"
                      :timestamp="formatDate(record.recordDate)"
                      placement="top"
                    >
                      <el-card>
                        <p>{{ record.conditionDescription }}</p>
                      </el-card>
                    </el-timeline-item>
                  </el-timeline>
                </div>
                <div v-else class="empty-data">
                  <el-empty description="暂无病情记录" />
                </div>
              </el-card>
            </el-tab-pane>
          </el-tabs>
        </el-col>
        <el-col :span="8">
          <el-card class="actions-card">
            <template #header>
              <div class="card-header">
                <span>快捷操作</span>
              </div>
            </template>
            <div class="action-buttons">
              <el-button type="primary" @click="handleEditDiagnosis">
                <el-icon><Edit /></el-icon> 添加诊断
              </el-button>
              <el-button type="success" @click="handleEditTreatment">
                <el-icon><SetUp /></el-icon> 添加治疗计划
              </el-button>
              <el-button type="warning" @click="handleAddConditionRecord">
                <el-icon><DocumentAdd /></el-icon> 添加病情记录
              </el-button>
              <el-button type="info" @click="handlePrintReport">
                <el-icon><Printer /></el-icon> 打印报告
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 诊断编辑对话框 -->
    <el-dialog
      title="编辑诊断信息"
      v-model="diagnosisDialogVisible"
      width="500px"
      append-to-body
    >
      <el-form ref="diagnosisFormRef" :model="diagnosisForm" :rules="diagnosisRules" label-width="100px">
        <el-form-item label="诊断结果" prop="diagnosisResult">
          <el-input 
            v-model="diagnosisForm.diagnosisResult" 
            type="textarea" 
            :rows="4" 
            placeholder="请输入诊断结果"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="diagnosisDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitDiagnosisForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 治疗计划编辑对话框 -->
    <el-dialog
      title="编辑治疗计划"
      v-model="treatmentDialogVisible"
      width="500px"
      append-to-body
    >
      <el-form ref="treatmentFormRef" :model="treatmentForm" :rules="treatmentRules" label-width="100px">
        <el-form-item label="治疗描述" prop="treatmentDescription">
          <el-input 
            v-model="treatmentForm.treatmentDescription" 
            type="textarea" 
            :rows="4" 
            placeholder="请输入治疗描述"
          />
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker
            v-model="treatmentForm.startDate"
            type="datetime"
            placeholder="选择开始日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker
            v-model="treatmentForm.endDate"
            type="datetime"
            placeholder="选择结束日期"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="treatmentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitTreatmentForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 病情记录编辑对话框 -->
    <el-dialog
      title="添加病情记录"
      v-model="conditionDialogVisible"
      width="500px"
      append-to-body
    >
      <el-form ref="conditionFormRef" :model="conditionForm" :rules="conditionRules" label-width="100px">
        <el-form-item label="病情描述" prop="conditionDescription">
          <el-input 
            v-model="conditionForm.conditionDescription" 
            type="textarea" 
            :rows="4" 
            placeholder="请输入病情描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="conditionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitConditionForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  User, 
  Edit, 
  Printer, 
  Calendar, 
  Phone,
  Plus,
  SetUp,
  DocumentAdd
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { listPatients, getPatients } from '@/api/patients'
import { 
  listDoctordiagnoses, 
  addDoctordiagnoses, 
  updateDoctordiagnoses, 
  delDoctordiagnoses 
} from '@/api/doctordiagnoses'
import { 
  listTreatmentplans, 
  addTreatmentplans, 
  updateTreatmentplans, 
  delTreatmentplans 
} from '@/api/treatmentplans'
import { 
  listConditionrecords, 
  addConditionrecords, 
  updateConditionrecords, 
  delConditionrecords 
} from '@/api/conditionrecords'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 患者数据
const patients = ref([])
const selectedPatientId = ref(null)
const selectedPatient = ref(null)
const loading = ref(false)

// 诊断相关数据
const diagnosisList = ref([])
const latestDiagnosis = computed(() => {
  if (diagnosisList.value.length === 0) return null
  return diagnosisList.value.sort((a, b) => new Date(b.diagnosisDate) - new Date(a.diagnosisDate))[0]
})

// 治疗计划相关数据
const treatmentPlansList = ref([])

// 病情记录相关数据
const conditionRecordsList = ref([])

// 标签页控制
const activeTab = ref('diagnosis')

// 对话框控制
const diagnosisDialogVisible = ref(false)
const treatmentDialogVisible = ref(false)
const conditionDialogVisible = ref(false)

// 表单数据
const diagnosisForm = reactive({
  id: null,
  patientId: null,
  doctorId: null,
  diagnosisResult: '',
  diagnosisDate: null
})

const treatmentForm = reactive({
  id: null,
  patientId: null,
  treatmentDescription: '',
  startDate: new Date(),
  endDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000) // 默认一周后结束
})

const conditionForm = reactive({
  id: null,
  patientId: null,
  conditionDescription: '',
  recordDate: null
})

// 表单验证规则
const diagnosisRules = {
  diagnosisResult: [{ required: true, message: '请输入诊断结果', trigger: 'blur' }]
}

const treatmentRules = {
  treatmentDescription: [{ required: true, message: '请输入治疗描述', trigger: 'blur' }],
  startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }]
}

const conditionRules = {
  conditionDescription: [{ required: true, message: '请输入病情描述', trigger: 'blur' }]
}

// 表单引用
const diagnosisFormRef = ref(null)
const treatmentFormRef = ref(null)
const conditionFormRef = ref(null)

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化日期为后端需要的格式
const formatDateForBackend = (date) => {
  if (!date) return null
  
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 获取患者列表
const getPatientList = async () => {
  loading.value = true
  try {
    const response = await listPatients()
    patients.value = response
    
    // 如果URL中有patientId参数，则选中对应患者
    const patientId = route.query.patientId
    if (patientId) {
      selectedPatientId.value = parseInt(patientId)
      handlePatientChange(selectedPatientId.value)
    }
  } catch (error) {
    console.error('获取患者列表失败:', error)
    ElMessage.error('获取患者列表失败')
  } finally {
    loading.value = false
  }
}

// 处理患者选择变化
const handlePatientChange = async (patientId) => {
  if (!patientId) return
  
  loading.value = true
  try {
    // 获取患者详情
    const patientResponse = await getPatients(patientId)
    selectedPatient.value = patientResponse
    
    // 更新URL参数
    router.push({
      query: { ...route.query, patientId }
    })
    
    // 加载诊断记录
    await loadDiagnosisList(patientId)
    
    // 加载治疗计划
    await loadTreatmentPlansList(patientId)
    
    // 加载病情记录
    await loadConditionRecordsList(patientId)
    
  } catch (error) {
    console.error('获取患者详情失败:', error)
    ElMessage.error('获取患者详情失败')
  } finally {
    loading.value = false
  }
}

// 加载诊断记录列表
const loadDiagnosisList = async (patientId) => {
  try {
    const response = await listDoctordiagnoses({ patientId })
    diagnosisList.value = response
  } catch (error) {
    console.error('获取诊断记录失败:', error)
    ElMessage.error('获取诊断记录失败')
  }
}

// 加载治疗计划列表
const loadTreatmentPlansList = async (patientId) => {
  try {
    const response = await listTreatmentplans({ patientId })
    treatmentPlansList.value = response
  } catch (error) {
    console.error('获取治疗计划失败:', error)
    ElMessage.error('获取治疗计划失败')
  }
}

// 加载病情记录列表
const loadConditionRecordsList = async (patientId) => {
  try {
    const response = await listConditionrecords({ patientId })
    conditionRecordsList.value = response
  } catch (error) {
    console.error('获取病情记录失败:', error)
    ElMessage.error('获取病情记录失败')
  }
}

// 处理编辑诊断
const handleEditDiagnosis = () => {
  if (!selectedPatient.value) {
    ElMessage.warning('请先选择患者')
    return
  }
  
  // 重置表单
  diagnosisForm.id = null
  diagnosisForm.patientId = selectedPatient.value.id
  diagnosisForm.doctorId = parseInt(userStore.id)
  diagnosisForm.diagnosisResult = ''
  diagnosisForm.diagnosisDate = null
  
  diagnosisDialogVisible.value = true
}

// 处理编辑治疗计划
const handleEditTreatment = () => {
  if (!selectedPatient.value) {
    ElMessage.warning('请先选择患者')
    return
  }
  
  // 重置表单
  treatmentForm.id = null
  treatmentForm.patientId = selectedPatient.value.id
  treatmentForm.treatmentDescription = ''
  treatmentForm.startDate = new Date()
  treatmentForm.endDate = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
  
  treatmentDialogVisible.value = true
}

// 处理添加病情记录
const handleAddConditionRecord = () => {
  if (!selectedPatient.value) {
    ElMessage.warning('请先选择患者')
    return
  }
  
  // 重置表单
  conditionForm.id = null
  conditionForm.patientId = selectedPatient.value.id
  conditionForm.conditionDescription = ''
  conditionForm.recordDate = null
  
  conditionDialogVisible.value = true
}

// 提交诊断表单
const submitDiagnosisForm = () => {
  diagnosisFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await addDoctordiagnoses(diagnosisForm)
        ElMessage.success('添加诊断成功')
        diagnosisDialogVisible.value = false
        
        // 重新加载诊断记录
        await loadDiagnosisList(selectedPatient.value.id)
      } catch (error) {
        console.error('添加诊断失败:', error)
        ElMessage.error('添加诊断失败')
      }
    }
  })
}

// 提交治疗计划表单
const submitTreatmentForm = () => {
  treatmentFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 格式化日期为后端需要的格式
        const formData = {
          ...treatmentForm,
          startDate: formatDateForBackend(treatmentForm.startDate),
          endDate: formatDateForBackend(treatmentForm.endDate)
        }
        
        await addTreatmentplans(formData)
        ElMessage.success('添加治疗计划成功')
        treatmentDialogVisible.value = false
        
        // 重新加载治疗计划
        await loadTreatmentPlansList(selectedPatient.value.id)
      } catch (error) {
        console.error('添加治疗计划失败:', error)
        ElMessage.error('添加治疗计划失败')
      }
    }
  })
}

// 提交病情记录表单
const submitConditionForm = () => {
  conditionFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await addConditionrecords(conditionForm)
        ElMessage.success('添加病情记录成功')
        conditionDialogVisible.value = false
        
        // 重新加载病情记录
        await loadConditionRecordsList(selectedPatient.value.id)
      } catch (error) {
        console.error('添加病情记录失败:', error)
        ElMessage.error('添加病情记录失败')
      }
    }
  })
}

// 处理打印报告
const handlePrintReport = () => {
  ElMessage.info('打印功能开发中...')
}

// 生命周期钩子
onMounted(() => {
  getPatientList()
})
</script>

<style scoped>
.diagnosis-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h1 {
  font-size: 24px;
  color: #303133;
  margin: 0;
}

.patient-selector {
  display: flex;
  align-items: center;
  gap: 10px;
}

.patient-select {
  width: 250px;
}

.patient-option {
  display: flex;
  align-items: center;
}

.patient-option-info {
  margin-left: 10px;
}

.patient-option-id {
  font-size: 12px;
  color: #909399;
}

.patient-info-card {
  margin-bottom: 20px;
}

.patient-info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.patient-basic-info {
  display: flex;
  flex-direction: column;
}

.patient-basic-info h2 {
  margin: 0 0 10px 0;
  font-size: 20px;
}

.patient-details {
  display: flex;
  gap: 20px;
  align-items: center;
  flex-wrap: wrap;
}

.patient-actions {
  display: flex;
  gap: 10px;
}

.diagnosis-content {
  margin-top: 20px;
}

.diagnosis-tabs {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.diagnosis-section {
  margin-bottom: 20px;
}

.diagnosis-section h3 {
  font-size: 16px;
  margin-bottom: 10px;
  color: #606266;
}

.diagnosis-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.diagnosis-result {
  font-weight: bold;
}

.diagnosis-date {
  color: #909399;
  font-size: 12px;
}

.treatment-section {
  margin-bottom: 20px;
}

.treatment-section h3 {
  font-size: 16px;
  margin-bottom: 10px;
  color: #606266;
}

.empty-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.actions-card {
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
</style> 